/**
 * 全局插件配置资源（vue插件部分）
 * @module utils/plugin
 */
import { elIcons, ionicons5, carbon } from './icon';
import bus from '@u/bus';
import router from '@/router';

// 指令
import hasPermi from './directives/hasPermi';

// 全局组件
import { components } from '@c/publicConfig';

/**模块store数据 */
import Com from '@s/com';
import Dict from '@s/dict';
import Guarder from '@s/guarder';
import User from '@s/user';
import Chart from '@s/chart/index';

/**方法 */
import { selectDictLabel } from './util';
import { confirm, msgError } from './autoImport';
import { cloneDeep } from 'lodash';

export default function (app) {
	// svg字体图标
	const svgModules = import.meta.glob('../assets/svg/*.svg');
	for (const key of Object.keys(svgModules)) {
		User().svgIcons.push(/^(?:\.\.\/assets\/svg\/)(\S+)(?:\.svg)/gi.exec(key).at(1));
	}
	// 字体图标
	[ionicons5, carbon, elIcons].forEach((item) => {
		for (const [key, component] of Object.entries(item)) {
			if (!app.component(key)) {
				app.component(key, component);
				User().elIcons.push(key);
			}
		}
	});

	/**
	 * 全局指令
	 */
	app.directive('hasPermi', hasPermi);

	// 全局配置基础组件信息
	for (const [key, value] of Object.entries(components)) {
		// 防止组件重复注册
		if (!app.component(key)) app.component(key, value);
	}

	/**
	 * 原型链全局挂载方法
	 */
	window['$router'] = app.config.globalProperties.$router = router;
	window['$store'] = app.config.globalProperties.$store = {
		com: Com(),
		dict: Dict(),
		guarder: Guarder(),
		user: User(),
		chart: Chart()
	};
	window['$bus'] = app.config.globalProperties.$bus = bus;
	window['selectDictLabel'] = app.config.globalProperties.selectDictLabel = selectDictLabel;
	window['resetForm'] = app.config.globalProperties.resetForm = function (refName) {
		if (refName) {
			// 不是公用的my-form标签的ref逻辑
			refName?.resetFields?.() || refName?.$refs?.refMyForm?.resetFields?.();
		}
	};
	window['confirm'] = confirm;
	window['msgError'] = msgError;
	window['cloneDeep'] = cloneDeep;

	/**
	 * vite动态加载图片静态文件
	 * @param {string} path 文件路径
	 * @returns
	 */
	const modules = import.meta.glob('../assets/img/**/*', { eager: true });
	app.config.globalProperties.getImgUrl = (path) => {
		if (path && modules) {
			if (path.includes('../assets/img/')) {
				return modules[path].default;
			} else {
				return modules[`../assets/img/${path}`].default;
			}
		}
	};
}
